package com.billdowney.qq.robot.util;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpUtils;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {
	private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
	/**
	 * 带参数的get请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doGet(String url, Map<String, String> param) {
			System.out.println(param.toString()+"=================");
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
 
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			System.out.println("GET请求执行了");
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			System.out.println(httpGet.toString());
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}

	/**
	 * 不带参数的get请求
	 * @param url
	 * @return String
	 */
	public static String doGet(String url) {

		return doGet(url, null);
	}




	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);

			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}










	/**
	 * 不带参数的post请求
	 * @param url
	 * @return String
	 */
	public static String doPost(String url) {
		return doPost(url, null);
	}
	
	/**
	 * 传送json类型的post请求
	 * @param url
	 * @param json
	 * @return String
	 */
	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容

			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 * @param url 发送请求的 URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(String url, String param,String Authorization,String contentType)
	{
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try
		{
			String urlNameString = url;
			log.info("sendPost - {}", urlNameString);
			URL realUrl = new URL(urlNameString);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			if(Authorization!=null){conn.setRequestProperty("Authorization",Authorization);}
			conn.setRequestProperty("Content-Type", contentType);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(conn.getOutputStream());
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null)
			{
				result.append(line);
			}
			log.info("recv - {}", result);
		}
		catch (ConnectException e)
		{
			log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
		}
		catch (SocketTimeoutException e)
		{
			log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
		}
		catch (IOException e)
		{
			log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
		}
		catch (Exception e)
		{
			log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
		}
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			}
			catch (IOException ex)
			{
				log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
			}
		}
		return result.toString();
	}





	public static String sendPosts(String url, String param)
	{
		PrintWriter out = null;
		BufferedReader in = null;
		StringBuilder result = new StringBuilder();
		try
		{
			String urlNameString = url;
			log.info("sendPost - {}", urlNameString);
			URL realUrl = new URL(urlNameString);
			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Accept-Charset", "utf-8");
			//conn.setRequestProperty("Authorization",Authorization);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setDoOutput(true);
			conn.setDoInput(true);
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(),"UTF-8"));
			out.print(param);
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

			String line;
			while ((line = in.readLine()) != null)
			{
				result.append(line);
			}
			log.info("recv - {}", result);
		}
		catch (ConnectException e)
		{
			log.error("调用HttpUtils.sendPost ConnectException, url=" + url + ",param=" + param, e);
		}
		catch (SocketTimeoutException e)
		{
			log.error("调用HttpUtils.sendPost SocketTimeoutException, url=" + url + ",param=" + param, e);
		}
		catch (IOException e)
		{
			log.error("调用HttpUtils.sendPost IOException, url=" + url + ",param=" + param, e);
		}
		catch (Exception e)
		{
			log.error("调用HttpsUtil.sendPost Exception, url=" + url + ",param=" + param, e);
		}
		finally
		{
			try
			{
				if (out != null)
				{
					out.close();
				}
				if (in != null)
				{
					in.close();
				}
			}
			catch (IOException ex)
			{
				log.error("调用in.close Exception, url=" + url + ",param=" + param, ex);
			}
		}
		return result.toString();
	}








//	public static String doPostad(String strUrl, String content) {
//		String result = "";
//
//		try {
//			URL url = new URL(strUrl);
//			//通过调用url.openConnection()来获得一个新的URLConnection对象，并且将其结果强制转换为HttpURLConnection.
//			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//			urlConnection.setRequestMethod("POST");
//			//设置连接的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
//			urlConnection.setConnectTimeout(30000);
//			//设置读取的超时值为30000毫秒，超时将抛出SocketTimeoutException异常
//			urlConnection.setReadTimeout(30000);
//			//将url连接用于输出，这样才能使用getOutputStream()。getOutputStream()返回的输出流用于传输数据
//			urlConnection.setDoOutput(true);
//			//设置通用请求属性为默认浏览器编码类型
//			urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");
//			//getOutputStream()返回的输出流，用于写入参数数据。
//			OutputStream outputStream = urlConnection.getOutputStream();
//			outputStream.write(content.getBytes());
//			outputStream.flush();
//			outputStream.close();
//			//此时将调用接口方法。getInputStream()返回的输入流可以读取返回的数据。
//			InputStream inputStream = urlConnection.getInputStream();
//
//
//
//
//			byte[] data = new byte[1024];
//			StringBuilder sb = new StringBuilder();
//			//inputStream每次就会将读取1024个byte到data中，当inputSteam中没有数据时，inputStream.read(data)值为-1
//			while (inputStream.read(data) != -1) {
//				String s = new String(data, Charset.forName("utf-8"));
//				sb.append(s);
//			}
//			result = sb.toString();
//			inputStream.close();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//
//		return result;
//	}

//	public static void main(String[] args) {
//		String str = doPost("http://localhost:8888/task/", "firstName=Mickey%26&lastName=Mouse ");
//		System.out.println(str);
//	}







}
